package com.lzy.user.service.impl;

import com.lzy.enums.Sex;
import com.lzy.enums.UserStatus;
import com.lzy.exception.GraceException;
import com.lzy.grace.result.ResponseStatusEnum;
import com.lzy.pojo.AppUser;
import com.lzy.pojo.bo.UpdateUserInfoBO;
import com.lzy.user.mapper.AppUserMapper;
import com.lzy.user.service.UserService;
import com.lzy.utils.DateUtil;
import com.lzy.utils.DesensitizationUtil;
import com.lzy.utils.JsonUtils;
import com.lzy.utils.RedisOperator;
import idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    public AppUserMapper appUserMapper;

    @Autowired
    public RedisOperator redis;
    public static final String REDIS_USER_INFO = "redis_user_info";

    @Autowired
    public Sid sid;
    @Override
    public AppUser queryMobileIsExist(String mobile) {
        Example userExample = new Example(AppUser.class);
        Example.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andEqualTo("mobile", mobile);
        AppUser user = appUserMapper.selectOneByExample(userExample);
        return user;
    }

    private static final String USER_FACE0 = "https://img.shetu66.com/2023/04/25/1682405980883837.png";
    @Transactional
    @Override
    public AppUser createUser(String mobile) {

        /**
         * 互联网项目都要考虑可扩展性，
         * 如果未来业务发展，需要分库分表，
         * 那么数据库表主键id必须保证全局（全库）唯一，不得重复
         */
        String userId = sid.nextShort();

        AppUser user = new AppUser();
        user.setId(userId);
        user.setMobile(mobile);
        user.setNickname("用户" + DesensitizationUtil.commonDisplay(mobile));
        // 默认头像
        user.setFace(USER_FACE0);
        // 默认生日
        user.setBirthday(DateUtil.stringToDate("1900-01-01"));
        // 默认性别为 保密
        user.setSex(Sex.secret.type);
        // 默认用户状态为未激活
        user.setActiveStatus(UserStatus.INACTIVE.type);
        // 默认用户总收入
        user.setTotalIncome(0);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        appUserMapper.insert(user);

        return user;
    }

    @Transactional
    @Override
    public void updateUserInfo(UpdateUserInfoBO updateUserInfoBO) {

        // 获取用户Id
        String userId = updateUserInfoBO.getId();

        //保证双写一致，先删除redis中的数据，后更新数据库
        redis.del(REDIS_USER_INFO + ":" + userId);

        AppUser userInfo = new AppUser();
        BeanUtils.copyProperties(updateUserInfoBO, userInfo);

        userInfo.setUpdatedTime(new Date());
        userInfo.setActiveStatus(UserStatus.ACTIVE.type);

        int result = appUserMapper.updateByPrimaryKeySelective(userInfo);//Selective只会更新BO中已有的属性
        if (result != 1) { // 是否更新成功
            GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR);
        }

        //再次查询用户的最新信息放入redis中
        AppUser user = getUser(userId);
        redis.set(REDIS_USER_INFO + ":" + userId, JsonUtils.objectToJson(user));

        //缓存双删策略
        try {
            Thread.sleep(100);
            redis.del(REDIS_USER_INFO + ":" + userId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public AppUser getUser(String userId) {
        return appUserMapper.selectByPrimaryKey(userId);
    }
}
